<template>
  <div class="cvue-upload">
    <el-upload
      :class="cssClass"
      :ref="refEl"
      :action="actionUrl"
      :file-list="fileList"
      :show-file-list="isShowFileList"
      :accept="accept"
      :auto-upload="isAutoUpload"
      :multiple="false"
      :limit="1"

      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleBeforeupload"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :headers="accessToken"
      :http-request="uploadFile"
      :name="name"
      :data="fileParams">
      <template v-if="type === 1">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click.prevent="submitUpload">上传到服务器</el-button> -->
        <div slot="tip" class="el-upload__tip"><slot name="slotTip"></slot></div>
      </template>
      <template v-if="type === 2">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </template>
      <template v-if="type === 3">
        <div v-loading="fileLoading"><slot></slot></div>
      </template>
    </el-upload>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { decryptedData } from '@/utils/encrypt'
export default {
  name: 'upload',
  data () {
    return {
      uploadFileList: [],
      token: ''
    }
  },
  computed: {
    accessToken () {
      // JSON.parse(decryptedData(this.$store.getters['user/accessToken'])).session_key
      var accessToken = {
        'Authorization': '09164bc249a643f29bfb06a291984252'
      }
      return accessToken
    }
  },
  props: {
    type: {
      type: Number,
      default: 1
    },
    accept: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: 'file'
    },
    imageUrl: {
      type: String,
      default: ''
    },
    refEl: {
      type: String,
      default: 'cvue-upload'
    },
    cssClass: {
      type: String,
      default: ''
    },
    actionUrl: {
      type: String,
      default: 'https://jsonplaceholder.typicode.com/posts/'
    },
    headToken: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    fileParams: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    fileList: {
      type: Array,
      default: () => {
        return [] // 附件列表
      }
    },
    isShowFileList: {
      type: Boolean,
      default: false
    },
    fileLoading: {
      type: Boolean,
      default: false
    },
    isAutoUpload: {
      type: Boolean,
      default: true
    },
    uploadImg: {
      type: Function,
      default: () => {
        return () => {}
      }
    }
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.error(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 上传前
    handleBeforeupload (file) {
      // const isJPG = file.type === 'image/jpeg'
      // var pattern = ''
      // if (this.accept == '.xls,.xlsx') {
      //   pattern = /(\.jpg)|(\.png)|(\.jpeg)|(\.gif)/ig
      // } else {
      //   if (!pattern.test(file.name)) {
      //     this.$message({ message: '上传文件只支持jpg、png、jpeg、gif格式', type: 'error' })
      //     return false
      //   }
      // }
      // var m = (file.size / (1024 * 1024)).toFixed(2)
      // if (m > 30) {
      //   this.$message({ message: '最大限制30M', type: 'error' })
      //   return false
      // }
      // return true
      this.$emit('before-upload', file)
    },
    // 成功
    handleSuccess (response, file, fileList) {
      this.$emit('success', {response, file, fileList})
    },
    // 错误
    handleError (err, file, fileList) {
      var errData = JSON.parse(err.message)
      this.$message({ message: errData.resp_msg, duration: 5000, type: 'error' })
      this.$emit('error')
    },
    handleChange (file, fileList) {
      this.uploadFileList = fileList
      this.$emit('change', {file, fileList})
    },
    // 移除
    handleRemove (file, fileList) {
      this.$emit('remove', {file, fileList})
      // return true
    },
    // 预览
    handlePreview (file) {
      this.$emit('preview', file)
    },
    uploadFile (param) {
      this.$emit('http-request', param)
    },
    // 表单上传
    uploadFile1 (param) { 
      var fileObj = param.file
      var formData = new FormData()
      var fileObj = param.file
      var formData = new FormData()
      var params = {
        filename: ''
      }
      formData.append('MS_HttpContext', fileObj)
      formData.append('data', JSON.stringify(params))
      this.$store.dispatch('payroll/ExcelFilePreview', formData).then(res => {
        console.log(res)
      })
    },
    // base64上传
    uploadFile2 (param) {
      var imgFiles =  param.file
      var reader = new FileReader()
      reader.readAsDataURL(imgFiles)
      var imgSrc
      var self = this
      reader.onload = function (e) {
        imgSrc = e.target.result
        var params = {
          "file_name": "222.png",
          "file_base64": imgSrc.split(',')[1]
        }
        self.$store.dispatch('sys/UploadImageByBase64', params).then(res => {
          console.log(res)
        })
      }
    },
    // 将base64转换为blob
    baseToBlob (dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //将blob转换为file
    blobToFile (theBlob, fileName) {
      theBlob.lastModifiedDate = new Date();
      theBlob.name = fileName;
      return theBlob;
    },
    submitUpload () {
      this.$refs['cvue-upload'].submit()
      if (this.uploadFileList.length > 0) {
        this.$emit('submit')
      }
    },
    exportExcel (url) {
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
      }).then((res) => {
        var blob = new Blob([res], {
          type: 'application/vnd.ms-excel',
        })
        const link = document.createElement("a")
        link.href = window.URL.createObjectURL(blob)
        var dt = this.getDateTime()
        link.download = '驾驶员详情_' + dt + '.xls'
        link.click()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.img-upload{
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
  }
  .avatar {
    width: 130px;
    height: 130px;
    display: block;
  }
}
</style>
